var express = require('express');
var router = express.Router();
var request = require('request');
var formidable = require('formidable');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var fs = require('fs');
var redis = require('redis'),
    Rds_Port=6379,//端口号
    Rds_Host='127.0.0.1',//服务器ip地址
    Rds_Pwd='lovehh123',//服务器密码
    Rds_Options={auth_pass:Rds_Pwd};
var client = redis.createClient(Rds_Port,Rds_Host,Rds_Options);
var qiniu = require('qiniu');

client.on("ready",function (err) {
  console.log("数据库连接成功");
})

client.on("error", function (err) {
    console.log("Error " + err);
});

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index');
});
router.get('/index', function(req, res, next) {
  res.render('index');
});

router.get('/rule', function(req, res, next) {
  res.render('rule');
});

router.get('/register1', function(req, res, next) {
  res.render('register1');
});

router.get('/register2', function(req, res, next) {
  res.render('register2');
});

router.get('/share', function(req, res, next) {
  res.render('share');
});

//连接路由器
router.post('/api/baseInfo',function (req,res) {
  client.incr('uid');//创建 键名为uid的字符串类型键值对，每次有用户注册的数据传入时候，我们都会将uid自增1。
  client.get('uid',function (err,uid) {
    //建立索引集合，username--id
    client.set('username:'+req.body.name,uid);
    client.hmset(
      "user:"+uid,
      'username',req.body.name,
      'sex',req.body.sex,
      'birth',req.body.birth,
      'number',req.body.number,
      'email',req.body.email,
      'address',req.body.address,
      function (err,response) {
      if(err){
        return 0;
      }
      else {
        console.log(response);
        console.log('you success');
        res.send({id:uid});
      }
    })
  })
})

router.post('/api/uploadImg',multipartMiddleware,function (req,res,next) {
  console.log("Request handler 'upload' was called ");
  console.log('req:.................'+req);
  console.log('req.body:...............'+req.body);
  var uid=req.body.hId;
  console.log('id:'+uid);
  //定义一个上传文件
  var form = new formidable.IncomingForm();
  form.multiples=true;
  form.uploadDir="./tmp";//必须设置
  if (!fs.existsSync(form.uploadDir)) {
        fs.mkdirSync(form.uploadDir);
    };
  console.log('req.files.....................'+req.files);
  var files = req.files;

  console.log("parsing done");
  var name=files.photo.name;
  var avatarName='/'+Date.now()+'_'+name;
  var newPath=form.uploadDir+avatarName;
  console.log(newPath);
  var key=Date.now()+'_'+name;

  //files获得上传的文件
  console.log('开始上传');
  fs.rename(files.photo.path,newPath,function(err) {
    console.log('上传到本地!');
    if(err){
      console.log('wrong.....................'+err);
    }else{
      //构建上传策略函数
      console.log('........................................七牛开始上传');

      qiniu.conf.ACCESS_KEY='n25q_-1mw1yZa8v-Z7WbRqwja5UNzz6i2qly9z5h';
      qiniu.conf.SECRET_KEY = 'XzGn8BQs5MOIX1rzvXHuGHzeke8REu7yR7jYERcZ';
      //上传的空间
      var bucket='lalocal';
      function uptoken(bucket, key) {
        var putPolicy = new qiniu.rs.PutPolicy(bucket+":"+key);
        return putPolicy.token();
      }
      //生成上传 Token
      token = uptoken(bucket, key);
      //构造上传函数
      function uploadFile(uptoken, key, localFile) {
        var extra = new qiniu.io.PutExtra();
          qiniu.io.putFile(uptoken, key, localFile, extra, function(err, ret) {
            if(!err) {
              // 上传成功， 处理返回值
              console.log(ret.hash, ret.key, ret.persistentId);
              var imgPath='http://media.lalocal.cn/'+ret.key;
              client.hmset("user:"+uid,'imgPath',imgPath);
              res.redirect('/register2?id='+uid);
            } else {
              // 上传失败， 处理返回代码
              console.log(err);
              res.redirect('/register1?id='+uid);
            }
        });
      }
      //调用uploadFile上传
      uploadFile(token, key, newPath);
    }
  });//重命名
})

router.post('/api/localDetails',function (req,res,next) {
  uid=req.body.id;
  client.get('uid',function (err,uid) {
    //建立索引集合，username--id
    client.hmset(
      "user:"+uid,
      'place',req.body.place,
      'localWay',req.body.localWay,
      'record',req.body.record,
      'type',req.body.type,
      function (err) {
      if(err){
        return 0;
      }
      else {
        console.log('you submit');
        res.send({id:uid});
      }
    })
  })
})
module.exports = router;